import React from 'react';
import { createFragmentContainer, graphql } from 'react-relay';
import makeStyles from '@mui/styles/makeStyles';
import { useTheme } from '@mui/styles';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Grid';
import Chip from '@mui/material/Chip';
import { useFormatter } from '../../../../components/i18n';
import VulnerabilitySoftwares from './VulnerabilitySoftwares';
import ExpandableMarkdown from '../../../../components/ExpandableMarkdown';
import { emptyFilled } from '../../../../utils/String';
import ItemBoolean from '../../../../components/ItemBoolean';
import FieldOrEmpty from '../../../../components/FieldOrEmpty';

// Deprecated - https://mui.com/system/styles/basics/
// Do not use it for new code.
const useStyles = makeStyles(() => ({
  paper: {
    margin: '10px 0 0 0',
    padding: '15px',
    borderRadius: 4,
  },
  chip: {
    fontSize: 12,
    lineHeight: '12px',
    height: 25,
    marginTop: 4,
    textTransform: 'uppercase',
    borderRadius: 4,
  },
}));

const inlineStyles = {
  whiteDark: {
    backgroundColor: '#ffffff',
    color: '#2b2b2b',
  },
  whiteLight: {
    backgroundColor: '#ffffff',
    color: '#2b2b2b',
    border: '1px solid #2b2b2b',
  },
  green: {
    backgroundColor: 'rgba(76, 175, 80, 0.08)',
    color: '#4caf50',
  },
  blue: {
    backgroundColor: 'rgba(92, 123, 245, 0.08)',
    color: '#5c7bf5',
  },
  red: {
    backgroundColor: 'rgba(244, 67, 54, 0.08)',
    color: '#f44336',
  },
  orange: {
    backgroundColor: 'rgba(255, 152, 0, 0.08)',
    color: '#ff9800',
  },
  black: {
    backgroundColor: '#000000',
    color: '#ffffff',
  },
};

const VulnerabilityDetailsComponent = ({ vulnerability }) => {
  const classes = useStyles();
  const theme = useTheme();
  const { t_i18n } = useFormatter();

  const getChipStyleFromCVSS3Score = (score) => {
    switch (true) {
      case score <= 3: return inlineStyles.green;
      case score <= 5: return inlineStyles.blue;
      case score <= 7: return inlineStyles.orange;
      case score <= 9: return inlineStyles.red;
      case score <= 10: return inlineStyles.black;
      default: return theme.palette.mode === 'light'
        ? inlineStyles.whiteLight
        : inlineStyles.whiteDark;
    }
  };
  const renderScore = (score) => {
    if (score === null) return '-';

    const chipStyle = getChipStyleFromCVSS3Score(score || 99);
    return (
      <Chip
        classes={{ root: classes.chip }}
        style={chipStyle}
        label={score}
      />
    );
  };

  const getChipStyleFromCVSS3Severity = (severity) => {
    switch (severity) {
      case 'LOW': return inlineStyles.green;
      case 'MEDIUM': return inlineStyles.orange;
      case 'HIGH': return inlineStyles.red;
      case 'CRITICAL': return inlineStyles.black;
      default: return {};
    }
  };

  const renderSeverity = (severity) => {
    if (!severity) return '-';

    const chipStyle = getChipStyleFromCVSS3Severity(severity);
    return (
      <Chip
        classes={{ root: classes.chip }}
        style={chipStyle}
        label={severity}
      />
    );
  };

  const renderKevContent = () => (
    <FieldOrEmpty source={vulnerability.x_opencti_cisa_kev}>
      <ItemBoolean
        status={vulnerability.x_opencti_cisa_kev}
        label={vulnerability.x_opencti_cisa_kev ? t_i18n('Yes') : t_i18n('No')}
        reverse={true}
      />
    </FieldOrEmpty>
  );

  return (
    <div style={{ height: '100%' }}>
      <Typography variant="h4" gutterBottom={true}>
        {t_i18n('Details')}
      </Typography>
      <Paper classes={{ root: classes.paper }} className={'paper-for-grid'} variant="outlined">
        <Typography variant="h3" gutterBottom={true}>
          {t_i18n('Description')}
        </Typography>
        <ExpandableMarkdown source={vulnerability.description} limit={400} />
        <Grid container={true} spacing={3}>
          <Grid item xs={6}>
            <Typography
              variant="h3"
              gutterBottom={true}
              style={{ marginTop: 15 }}
            >
              {t_i18n('CVSS3 - Score')}
            </Typography>
            {renderScore(vulnerability.x_opencti_cvss_base_score)}
          </Grid>
          <Grid item xs={6}>
            <Typography
              variant="h3"
              gutterBottom={true}
              style={{ marginTop: 15 }}
            >
              {t_i18n('CVSS3 - Severity')}
            </Typography>
            {renderSeverity(vulnerability.x_opencti_cvss_base_severity)}
          </Grid>
        </Grid>
        <Grid container={true} spacing={3}>
          <Grid item xs={6}>
            <Typography
              variant="h3"
              gutterBottom={true}
              style={{ marginTop: 15 }}
            >
              {t_i18n('CVSS3 - Availability impact (A)')}
            </Typography>
            <pre>{emptyFilled(vulnerability.x_opencti_cvss_availability_impact)}</pre>
          </Grid>
          <Grid item xs={6}>
            <Typography
              variant="h3"
              gutterBottom={true}
              style={{ marginTop: 15 }}
            >
              {t_i18n('CVSS3 - Integrity impact (I)')}
            </Typography>
            <pre>{emptyFilled(vulnerability.x_opencti_cvss_integrity_impact)}</pre>
          </Grid>
          <Grid item xs={6}>
            <Typography variant="h3" gutterBottom={true}>
              {t_i18n('CVSS3 - Confidentiality impact (C)')}
            </Typography>
            <pre>
              {emptyFilled(vulnerability.x_opencti_cvss_confidentiality_impact)}
            </pre>
          </Grid>
          <Grid item xs={6}>
            <Typography variant="h3" gutterBottom={true}>
              {t_i18n('CVSS3 - Attack vector (AV)')}
            </Typography>
            <pre>{emptyFilled(vulnerability.x_opencti_cvss_attack_vector)}</pre>
          </Grid>
          <Grid item xs={6}>
            <Typography variant="h3" gutterBottom={true}>
              {t_i18n('EPSS Score')}
            </Typography>
            <pre>{emptyFilled(vulnerability.x_opencti_epss_score)}</pre>
          </Grid>
          <Grid item xs={6}>
            <Typography variant="h3" gutterBottom={true}>
              {t_i18n('EPSS Percentile')}
            </Typography>
            <pre>{emptyFilled(vulnerability.x_opencti_epss_percentile)}</pre>
          </Grid>
          <Grid item xs={6}>
            <Typography variant="h3" gutterBottom={true}>
              {t_i18n('CISA KEV')}
            </Typography>
            {renderKevContent()}
          </Grid>
        </Grid>
        <VulnerabilitySoftwares vulnerability={vulnerability} />
      </Paper>
    </div>
  );
};

const VulnerabilityDetails = createFragmentContainer(
  VulnerabilityDetailsComponent,
  {
    vulnerability: graphql`
      fragment VulnerabilityDetails_vulnerability on Vulnerability {
        id
        x_opencti_cvss_base_score
        x_opencti_cvss_base_severity
        x_opencti_cvss_attack_vector
        x_opencti_cvss_integrity_impact
        x_opencti_cvss_availability_impact
        x_opencti_cvss_confidentiality_impact
        x_opencti_cisa_kev
        x_opencti_epss_score
        x_opencti_epss_percentile
        description
        ...VulnerabilitySoftwares_vulnerability
      }
    `,
  },
);

export default VulnerabilityDetails;
